package com.mbengue.corp.apr.ra.servlet;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.mbengue.corp.apr.ra.core.Image;
import com.mbengue.corp.apr.ra.dao.DAOFactory;
import com.mbengue.corp.apr.ra.dao.ImageDao;

public class ImageServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private static ImageDao imageDao = DAOFactory.getImageDao();

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Get ID from request.
    String imageId = request.getParameter("nom");
    // Check if ID is supplied to the request.
    if (imageId == null) {
      return;
    }
    // Lookup Image by ImageId in database.
    Image image = imageDao.trouverImage(imageId);
    // Check if image is actually retrieved from database.
    if (image == null) {
      image = new Image();
      image.setNom("Default.jpg");
      image.setDescription("Image par defaut");
      InputStream is = getClass().getClassLoader().getResourceAsStream("/images/default.jpg");
      image.setImage(IOUtils.toByteArray(is));
    }
    // Init servlet response.
    response.reset();
    response.setBufferSize(image.getImage().length);
    int index = image.getNom().lastIndexOf(".") + 1;
    String ext = image.getNom().substring(index);
    response.setContentType("image/" + ext);
    response.setHeader("Content-Length", String.valueOf(image.getImage().length));
    response.setHeader("Content-Disposition", "inline; filename=\"" + image.getNom() + "\"");
    // Prepare streams.
    BufferedOutputStream output = null;
    try {
      output = new BufferedOutputStream(response.getOutputStream(), image.getImage().length);
      // Write file contents to response.
      output.write(image.getImage());
    } finally {
      // Gently close streams.
      output.close();
    }
  }
}
